﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using Polly;
using System.Security.Cryptography;
using System.Text;

namespace openiddict.demo.Controllers
{
    [Route("api/account")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly ApplicationDbContext context;

        public AccountController(ApplicationDbContext context)
        {
            this.context = context;
        }
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("register")]
        public async Task<IActionResult> Register(RegisterModel model)
        {
            // 检查模型是否有效
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // 检查用户名是否已存在
            var existingUser = await context.Users.FirstOrDefaultAsync(u => u.UserName == model.Username);
            if (existingUser != null)
            {
                return BadRequest("Username already exists.");
            }

            // 创建新用户并存储密码哈希
            var user = new User
            {
                UserName = model.Username,
                Email = model.Email,
                PasswordHash = HashPassword(model.Password)
            };

            await context.Users.AddAsync(user);
            await context.SaveChangesAsync();

            // 返回注册成功的信息
            return Ok(new
            {
                Message = "Registration successful!",
                UserId = user.Id
            });
        }

        private string HashPassword(string password)
        {
            // 使用合适的方式哈希密码，例如使用 BCrypt
            // 这里仅作为示例使用简单的哈希方式
            using (var sha256 = SHA256.Create())
            {
                var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
                return Convert.ToBase64String(bytes);
            }
        }

        [HttpGet("xxxx")]
        public  string GetDemo()
        {
            Console.WriteLine($"{0}","OK");
            return $"Hello, OpenIddict!{0},{1},OK,OK";
        }

    }
}
